'use strict';
exports.main = async (event, context) => {
  const { userId, taskId, taskDate } = event;
  const db = uniCloud.database();
  const _ = db.command;

  try {
    // 1. 获取用户数据
    const userRes = await db.collection('user').doc(userId).get();
    if (!userRes.data) return { code: 404, msg: '用户不存在' };

    // 2. 验证任务是否已完成
    const today = formatDate(Date.now()).split(' ')[0];
    if (taskDate !== today) {
      return { code: 400, msg: '任务已过期' };
    }

    if (userRes.data.completedTasks && 
        userRes.data.completedTasks.includes(taskId)) {
      return { code: 400, msg: '任务已完成' };
    }

    // 3. 更新用户数据
    await db.collection('user').doc(userId).update({
      score: _.inc(getTaskReward(taskId)), // 需要实现 getTaskReward 函数
      completedTasks: _.push(taskId),
      lastTaskDate: today
    });

    return { code: 200, msg: '任务完成成功' };
  } catch (err) {
    console.error('任务处理失败:', err);
    return { code: 500, msg: '服务器错误' };
  }
};

// 获取任务奖励函数
function getTaskReward(taskId) {
  const rewards = {
    1: 20,
    2: 50,
    3: 30,
    4: 30
  };
  return rewards[taskId] || 0;
}
function formatDate(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
  const date = new Date(timestamp);
  
  const pad = (n) => n.toString().padStart(2, '0');
  
  const replacements = {
    YYYY: date.getFullYear(),
    MM: pad(date.getMonth() + 1),    // 月份从0开始需+1
    DD: pad(date.getDate()),
    HH: pad(date.getHours()),
    mm: pad(date.getMinutes()),
    ss: pad(date.getSeconds()),
    SSS: pad(date.getMilliseconds(), 3)
  };

  return format.replace(/YYYY|MM|DD|HH|mm|ss|SSS/g, match => replacements[match]);
}